// pages/game/play.js
const TRADIS = require('../../tradis/tradis.js');
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    go:false,
    board_id:'',
    iscanRevival:false,
    revival:0,
    borderindex: 0,
    borderlist:[],
    board:{},
    topic:{},
    rightanswer: {},
    tips:'',
    score:{},
    isFetch: true,
    answer: [],
    defaultarr: [],
    ciwords: [],
    defaultwords: [],
    nowindex: 0,
    istip:false,
    pageIn: 'detail',
    gotimer:null,
    gotime:3,
    showplus:false,
    money:false,
    music:{},
    music_321: {},
    // music_background:'',
    music_bingo: '',
    music_click: '',
    music_error: '',    
    music_over: '',  
    music_readygo: '',
    userInfo:{},
    isfirst:true,
    firsthide:false,
    isstar:false,
    iswrong:false,
    IMG_error:0,
    canPush:true,
    showjump:false,
    jumptime:null,

   
    
  
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
   
    wx.showShareMenu({
      withShareTicket: true
    })

    wx.hideShareMenu({})
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  
  },



  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    clearInterval(this.data.gotimer);
    // this.data.music_background.stop();
    this.data.music_321.stop();
    this.data.music_readygo.stop();

    // this.data.music_countdown.stop();
    console.log('unload');
    
  },
  /**
   * 生命周期函数--监听页面影藏
   */
  onHide:function(){
    console.log('onhide');
    
  },
    /**
   * 生命周期函数--监听页面显示
   */
  onShow:function(){
   console.log('onshow');
   TRADIS.tradis(this);
  //  if (this.data.music_background!=''){
  //    this.data.music_background.play();
  //  }
   if(this.data.isstar==false){
     let token = wx.getStorageSync('token');
     if (token) {
       this.gameStart();
       this.setData({
         userInfo: wx.getStorageSync('userInfo'),
       })
       
     } else {
       wx.navigateTo({
         url: '/pages/auth/getuserinfo',
       })
     } 
   }
   else{
     if (this.data.revival > 0 && this.data.iscanRevival){

       this.revival_fn();
       this.setData({
         iscanRevival:false,
         revival:0,
         iswrong: false,
       })
     }
   }
    
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  },
  /***
   * 图片加载错误
   **/
   IMG_Error:function(e){
      console.log('aaaaa');
      this.data.borderlist[this.data.borderindex].image = this.data.borderlist[this.data.borderindex].image+'&_t='+new Date().getTime();
      setTimeout(()=>{
        this.setData({
          borderlist: this.data.borderlist,
        })
      },1000);

      this.data.IMG_error++;
      if(this.data.IMG_error>3){
        this.data.IMG_error =0;
        wx.showToast({
          title: '网络异常',
          icon:'none',
          success:function(){
            setTimeout(function(){
              wx.redirectTo({
                url: '/pages/index/index',
              });
            },1500)

          },
        })

      }
   },
  /**
   * 加载音频资源文件
   */
  getMusic:function(){
        
          this.data.music_321 = wx.createInnerAudioContext()
          this.data.music_321.autoplay = false;
          this.data.music_321.src = '/music/music_321.mp3';

          this.data.music_readygo = wx.createInnerAudioContext();
          this.data.music_readygo.autoplay = false;
          this.data.music_readygo.src = '/music/music_readygo.mp3';

          this.data.music_bingo = wx.createInnerAudioContext();
          this.data.music_bingo.autoplay = false;
          this.data.music_bingo.src = '/music/music_bingo.mp3';

          this.data.music_error = wx.createInnerAudioContext();
          this.data.music_error.autoplay = false;
          this.data.music_error.src = '/music/music_error.mp3';

          this.data.music_click = wx.createInnerAudioContext();
          this.data.music_click.autoplay = false;
          this.data.music_click.src = '/music/music_click.mp3';

          this.data.music_over = wx.createInnerAudioContext();
          this.data.music_over.autoplay = false;
          this.data.music_over.src = '/music/music_over.mp3';
     
          this.data.music_321.onCanplay(()=>{
            this.data.music_321.play();
            this.data.music_321.offCanplay();
            this.data.gotimer = setInterval(() => {
           
           // console.log(this.data.gotime);
            if (this.data.gotime <= 0) {

              clearInterval(this.data.gotimer);
              this.setData({
                go: true
              })
              //开始题目
               this.fetchStart();
            }

            else {
              if (this.data.gotime == 1) {
                this.data.music_readygo.play();
                // setTimeout(()=>{
                //   this.data.music_background.play();
                // },3000)
              }
              this.data.gotime--;
              this.setData({
                gotime: this.data.gotime
              })
            }


          }, 1000);
          });
  },
  /**
   * 开始游戏，拉取当局游戏
   */
  gameStart:function(){
    wx.request({
      url: app.globalData.api + '/board/start.html&token=' + wx.getStorageSync('token'),
      method: 'get',
      success:(res)=>{
        if(res.data.code==0){
          this.setData({
            board_id: res.data.data.board_id,
            revival: res.data.data.revival,
            borderlist: res.data.data.list,
            isstar:true,
          })
          this.data.jumptime=setTimeout(()=>{
            this.setData({
              showjump:true,
            });
          },5*1000);
          this.getMusic();
         
          
        }
        else {
          this.fetchError(res.data.code,res.data.msg);
        }
      }
    })
  },
  /**
   * 跳过游戏
   */
  jumpTime:function(){
    this.setData({
      go:true,
    });
    this.fetchStart();
  },
   /**
   * 游戏进行中，拉取题目
   */
  fetchStart: function (){
    var detail = this.data.borderlist[this.data.borderindex];
    var ciwords = [];
    for (var i = 0; i < detail.words.length; i++) {
      var o = { "isactive": false, "word": detail.words[i] };
      ciwords.push(o);
    }
    var asw = [];
    for (var i = 0; i < 4; i++) {
      var o = { 'word': '', 'index': i, 'disable': false };
      asw.push(o);
    }
    this.setData({
      ciwords: ciwords,
      defaultwords: ciwords,
      answer: asw,
      defaultarr: asw,
      nowindex: 0,
    });
  },
  /**
   * 游戏进行中，删除单个
   */
  deleteWord(e) {
    this.data.music_click.stop();
    this.data.music_click.play();
    //console.log(e);
    wx.vibrateShort();
    this.data.answer[e.currentTarget.dataset.index].word = "";
    this.data.answer[e.currentTarget.dataset.index].index = "";
    this.data.nowindex = this.data.nowindex - 1;
    this.data.ciwords[e.currentTarget.dataset.ciwordsindex].isactive = false;
    this.setData({
      answer: this.data.answer,
      nowindex: this.data.nowindex,
      ciwords: this.data.ciwords
    })
  },
  /**
   * 游戏进行中，点击字体
   */
  setAnswer(e) {
    this.data.music_click.stop();
    this.data.music_click.play();
    wx.vibrateShort();
    this.setData({
      error: false,
    })
    if ((this.data.nowindex) >= 4) {
      this.pushAnswer();
      return false;
    }
    else {
      //console.log(e.currentTarget.dataset.index);
      var _this = this;
      for (var i = 0; i < 4; i++) {
        if (_this.data.answer[i].word == "") {
          var o = {
            word: _this.data.ciwords[e.currentTarget.dataset.index].word,
            ciwordsindex: e.currentTarget.dataset.index,
          }
          _this.data.answer[i] = o;
          break;
        }
      }
      this.data.ciwords[e.currentTarget.dataset.index].isactive = true;
      this.setData({
        ciwords: this.data.ciwords
      })
      if ((this.data.nowindex + 1) >= 4) {
       // console.log("打好了");
        this.pushAnswer();

        this.data.nowindex++;
      }
      else {
        this.data.nowindex++;
      }

      this.setData({
        answer: this.data.answer,
        nowindex: this.data.nowindex,
      })
    }
  },
  /**
   * 游戏进行中，发送答案
   */
  pushAnswer(help) {
    var _this = this;
    if (this.data.canPush==false){
      return false;
    }
    this.data.canPush = false;
    var words = "";
    for (var i = 0; i < this.data.answer.length; i++) {
      words += this.data.answer[i].word;
    }
    if (app.globalData.md5.hex_md5(wx.getStorageSync('token') + words) != _this.data.borderlist[_this.data.borderindex].idiom_key) {
      this.data.music_error.play();
      wx.vibrateLong();
      //console.log('错误');
      _this.setData({
        error: true,
        cantishi:true,
        canPush: true,
        iswrong:true,
        iscanRevival:true,
      })
      setTimeout(function () {
        _this.setData({
          error: false,
        })
      }, 3000);
      _this.data.rightanswer = _this.data.borderlist[_this.data.borderindex];
      // _this.data.rightanswer.idiom = words;
      _this.data.rightanswer.idiom = this.strencode(_this.data.borderlist[_this.data.borderindex].idiom);
      _this.setData({
        rightanswer: _this.data.rightanswer,
      });

      _this.gameEnd(0, _this.data.borderlist[_this.data.borderindex].id);

    }
    else {
          _this.data.music_bingo.play();
          _this.setData({
            canPush:true,
          })
        // clearInterval(_this.data.timer);
          // _this.data.music_countdown.pause();
          if (_this.data.borderindex >= (this.data.borderlist.length-1)){
            _this.gameEnd(1, _this.data.borderlist[_this.data.borderindex].id);
          }
          else{
            _this.data.rightanswer = _this.data.borderlist[_this.data.borderindex];
           // _this.data.rightanswer.idiom = words;
            _this.data.rightanswer.idiom = this.strencode(_this.data.borderlist[_this.data.borderindex].idiom);
            _this.setData({
              rightanswer: _this.data.rightanswer,
              istip: true,
            });
            // if ((1 + _this.data.borderindex) % 5 == 0) {
            //   _this.setData({
            //     innerad: [],
            //   });
            //   TRADIS.tradis(_this);
            // }

          }

   }
   /*答题记录上传*/
    wx.request({
      url: app.globalData.api + '/topic/answer.html&token=' + wx.getStorageSync('token'),
      method: 'post',
      data: {
        "board_id": _this.data.board_id,
        "question_id": _this.data.borderlist[_this.data.borderindex].id,
        "user_answer": words
      },
      success: (res2) => {
        console.log(res2);


      }
    })



  },
  /*游戏结束*/
  gameEnd:function(status,id){
    wx.request({
      url: app.globalData.api + '/board/end.html&token=' + wx.getStorageSync('token'),
      method: 'post',
      data: {
        "board_id": this.data.board_id,
        "is_complete": status,
        "question_id": id,
      },
      success: (res) => {
        console.log(res);
        if(status==1){      
          console.log('/pages/game/win?id=' + res.data.data.bonus.id + '&fee=' + res.data.data.bonus.fee + "&type=" + res.data.data.bonus.type + '&grade=' + JSON.stringify(res.data.data.grade));
          wx.redirectTo({
            url: '/pages/game/win?id=' + res.data.data.bonus.id + '&fee=' + res.data.data.bonus.fee + "&type=" + res.data.data.bonus.type + '&grade=' + JSON.stringify(res.data.data.grade),
          })
        }

      }
    })
  },
  /**
   * 游戏进行中，继续
   */
  continue_fn:function(){
  
    this.setData({
      istip:false,
    })
    var index = this.data.borderindex+1;
    this.setData({
      borderindex: index,
    })
    this.fetchStart();
    
  },
  /**
 * 游戏进行中，复活继续
 */
  revival_fn: function () {
    wx.showToast({
      title: '跳过成功',
    });
    if (this.data.borderindex==9){
      this.setData({
        istip: false,
      })
      var index = this.data.borderindex;
    }
    else{
      var index = this.data.borderindex + 1;
    }
    this.setData({
      borderindex: index,
    })
    this.fetchStart();
    wx.request({
      url: app.globalData.api + '/board/revival.html&token=' + wx.getStorageSync('token'),
      method: 'post',
      data: {
        "board_id": this.data.board_id,
      },
      success: (res2) => {
        console.log(res2);
      }
    })

  },
   /**
   * 游戏结束，再来一起
   */
  again_fn:function(){
    wx.redirectTo({
      url: '/pages/game/play',
    })
    // this.setData({
    //   istip: false,
    //   iswrong:false,
    //   go: false,
    //   board_id: '',
    //   borderindex: 0,
    // })
    // this.gameStart();
  },
  /**
   * 游戏进行中，清理
   */
  clear() {
   // console.log('清理');
    var nowindex = 0;
    this.setData({
      answer: this.data.defaultarr,
      ciwords: this.data.defaultwords,
    })
    this.data.answer.forEach(function (v, i) {
      if (v.word != '') {
        nowindex++;
      }
    })
    this.setData({
      nowindex: nowindex,
    })

  },
  /**
   * 游戏进行中，数据异常处理
   */
  fetchError:function(code,msg){
    if(code==40001){
      wx.navigateTo({
        url: '/pages/auth/getuserinfo',
      })
    }
    else{
      // wx.showModal({
      //   title: '错误',
      //   content: msg,
      //   success:function(){
      //     wx.navigateBack({
      //       delta: 1,
      //     })
      //   }
      // })
      wx.redirectTo({
        url: '/pages/index/index',
      })
    }

  },
  strencode: function(str) {
        var key =wx.getStorageSync('token');
        str = app.globalData.Base64.decode(str); 
        var len = key.length;   
        var code = '';   
        for (var i = 0; i < str.length; i++) {   
          var k = i % len;
          code += String.fromCharCode(str.charCodeAt(i) ^ key.charCodeAt(k));
        }
        return app.globalData.Base64.decode(code);   
  }


})